<template>
  <el-container>
    <template #default="scope">
      <el-row class="row-bg" gutter="150">
        <el-col :span="6">
          <el-input
            v-model="name"
            placeholder="请输入你要查询的信息"
            size="large"
            type="text"
            @keyup.enter="search"
            clearable
            style="margin: 1px"
        /></el-col>
        <el-col :span="4" class="grid-content ep-bg-purple" style="margin: 1px"
          ><el-button type="primary" size="default" plain @click="refresh">
            <el-icon style="vertical-align: middle">
              <el-icon>
                <Loading />
              </el-icon>
            </el-icon>
            <span style="vertical-align: middle">刷新实验室信息</span>
          </el-button></el-col
        >
        <el-col :span="4" class="grid-content ep-bg-purple">
          <el-button
            type="primary"
            size="default"
            @click="add(scope.$index, scope.row)"
            ><el-icon> <Edit /> </el-icon>添加实验室信息</el-button
          ></el-col
        >
        <el-col :span="4" class="grid-content ep-bg-purple" style="margin: 1px">
          <el-button type="primary" size="default" @click="modifyEdit"
            ><el-icon> <Edit /> </el-icon>修改实验室信息</el-button
          ></el-col
        >
        <el-col :span="4" class="grid-content ep-bg-purple" style="margin: 1px"
          ><el-button size="default" type="danger" @click="deleteRow"
            ><el-icon> <Delete /> </el-icon>删除实验室</el-button
          ></el-col
        >
      </el-row>
    </template>
  </el-container>
  <el-main>
    <el-table
      ref="singleTableRef"
      :data="tableData"
      style="width: 100%"
      max-height="75vh"
      height="75vh"
      size="large"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      @row-click="setValue"
      highlight-current-row
      v-loading="loading"
      element-loading-text="Loading..."
      :element-loading-spinner="svg"
      element-loading-svg-view-box="-10, -10, 50, 50"
      element-loading-background=""
    >
      <el-table-column fixed prop="id" label="实验室编号" />
      <el-table-column prop="name" label="实验室名称:" />
      <el-table-column prop="pic" label="图片">
        <template #default="scope">
          <img :src="scope.row.pic" class="image"
        /></template>
      </el-table-column>
      <el-table-column prop="device" label="实验室设备" />

      <el-table-column prop="time" label="可使用时间" width="110" />

      <el-table-column prop="number" label="数量" />
    </el-table>

    <!-- 弹框 开始 -->
    <el-dialog
      v-model="dialogVisible"
      :title="actionNme"
      width="30%"
      destroy-on-close
      center
    >
      <el-form :model="editedData" label-width="100px">
        <el-form-item label="实验室名称">
          <el-input v-model="editedData.name"></el-input>
        </el-form-item>
        <el-form-item label="实验室图片">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8081/file/updatePic"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="editedData.pic" :src="editedData.pic" class="avatar" />
            <el-icon v-else class="el-icon-plus avatar-uploader-icon"><Plus/></el-icon>
            
          </el-upload>
        </el-form-item>
        <el-form-item label="实验室设备">
          <el-input v-model="editedData.device"></el-input>
        </el-form-item>
        <el-form-item label="可使用时间">
          <el-date-picker
            v-model="editedData.time"
            type="datetime"
            placeholder="Pick a Date"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="MMM DD, YYYY"
            time-format="HH:mm"
          />
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="editedData.number"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="method">{{actionBution}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 弹框结束 -->
  </el-main>
</template>

<script>
import axios from "axios";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
export default {
  name: "Addgood",
  props: {
    msg: String,
  },
  data() {
    return {
      actionNme: "",
      actionBution:"",
      loading: false,
      tableData: [],
      editedData: {},
      name: "",
      value: {
        id: "",
        pic:""
      },
      dialogVisible: false,
    };
  },

  methods: {
    //搜索
    search() {
      axios
        .post("http://localhost:8081/laboratory/list", {
          name: this.name,
        })
        .then((res) => {
          if (res.status === 200) {
            this.tableData = res.data;
          }
        })
        .catch((error) => {
          ElMessage.error("网络错误：" + error);
        });
    },
    //刷新
    refresh() {
      this.loading = true;

      if (this.loading) {
        var loadingTime = setInterval(() => {
          this.loading = false;
          clearInterval(loadingTime);
        }, 1000);
      }
      axios.post("http://localhost:8081/laboratory/list", {}).then((res) => {
        if (res.status === 200) {
          ElMessage({
            message: "刷新信息成功",
            type: "success",
          });
          this.tableData = res.data;
        }
      });
    },

    setValue(value) {
      this.value = value;
    },
    // 上传头像前的处理
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "webp/jpeg";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
      }
      return isJPG;
    },
    // 上传头像成功后的处理
    handleAvatarSuccess(response, file) {
      this.editedData.pic = response;
      // URL.createObjectURL(file.raw);
      // 你也可以在这里处理服务端返回的图像链接，具体取决于你的后端实现
    },
    //添加按钮
    add() {
      this.actionNme = "添加实验室信息";
      this.actionBution="添加"
      console.log(this.value);
      this.editedData = {};
      this.dialogVisible = true;
    },
    //修改按钮
    modifyEdit() {
      if (this.value.id == 0) {
        ElNotification({
          title: "Warning",
          message: "未被选中",
          type: "warning",
        });
      } else {
        this.actionNme = "修改实验室信息";
        this.actionBution="保存修改"
        console.log(this.value);
        this.editedData = { ...this.value }; // 使用对象的拷贝，确保引用不共享
        console.log(this.editedData);
        console.log(this.dialogVisible);

        this.dialogVisible = true;
        console.log(this.dialogVisible);
      }
    },

    method() {
      debugger
      if (this.actionNme == "添加实验室信息") {
        this.saveAdd();
      } else {
        this.saveChanges();
      }
    },

    //保存添加的信息
    saveAdd() {
      console.log("添加",this.editedData);
      axios
        .post("http://localhost:8081/laboratory/save", { ...this.editedData })
        .then((res) => {
          this.search();
          ElMessage({
            message: "保存成功id为" + this.value.id + "的信息",
            type: "success",
          });
        })
        .catch((error) => {
          ElMessage.error("保存失败，网络错误：" + error);
        });
      // 关闭对话框
      this.dialogVisible = false;
      this.editedData = {};
    },
    saveChanges() {
      // 在这里处理保存修改后的数据
      console.log("保存修改后的数据:", this.editedData);
      axios
        .post("http://localhost:8081/laboratory/update", { ...this.editedData })
        .then((res) => {
          this.search();
          ElMessage({
            message: "修改成功id为" + this.value.id + "的信息",
            type: "success",
          });
        })
        .catch((error) => {
          ElMessage.error("修改失败，网络错误：" + error);
        });
      // 关闭对话框
      this.dialogVisible = false;
      this.editedData = {};
    },
    //删除
    deleteRow() {
      if (this.value.id == 0) {
        ElNotification({
          title: "实验室信息",
          message: "未被选中",
          type: "warning",
        });
      } else {
        ElMessageBox.confirm(
          "确定删除编号为" + this.value.id + "的信息吗?",
          "Warning",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then((res, action) => {
          axios
            .post("http://localhost:8081/laboratory/delete", {
              id: this.value.id,
            })
            .then((res) => {
              this.search();
              ElMessage({
                message: "删除成功实验室id为" + this.value.id + "的信息",
                type: "success",
              });
            })
            .catch((error) => {
              ElMessage.error("删除失败，网络错误：" + error);
            });
        });
      }
    },
    getTabelInfo() {
      axios
        .post("http://localhost:8081/laboratory/list", {
          name: this.name,
          pic: this.url,
          time: this.time,
          device: this.device,
          number: this.number,
        })
        .then((response) => {
          this.tableData = response.data;
          console.log(response.data); //请求正确时执行的代码
        })
        .catch(function (response) {
          console.log(response); //发生错误时执行的代码
        });
    },
  },
  mounted() {
    console.log("Dialog Visible:", this.dialogVisible);
    console.log("Edited Data:", this.editedData);
    this.getTabelInfo();
  },
};
const goBack = () => {
  console.log("go back");
};
</script>
<style>
.image {
  height: 80px;
}

.avatar-uploader {
  font-size: 0;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  overflow: hidden;
}

.avatar {
  width: 78px;
  height: 78px;
  border-radius: 4px;
}

.avatar-uploader-icon {
  margin-top: 25px;
  font-size: 28px;
  color: #8c939d;
}
</style>